﻿#include "FITKAFLRMeshProcessor.h"
#include "FITK_Interface/FITKInterfaceMesh/FITKUnstructuredFluidMeshVTK.h"
#include "FITK_Kernel/FITKAppFramework/FITKAppFramework.h"
#include "FITK_Kernel/FITKAppFramework/FITKGlobalData.h"
#include "FITK_Component/FITKOFMeshIO/FITKOFMeshReader.h"
#include "FITK_Kernel/FITKAppFramework/FITKComponents.h"
#include "FITK_Interface/FITKInterfaceFlowOF/FITKOFGeometryData.h"
#include "FITK_Interface/FITKInterfaceGeometry/FITKAbsGeoCommand.h"

#include <QDir>
#include <QDebug>


namespace AFLR
{
    void FITKAFLRMeshProcessor::start(QStringList info /*= QStringList()*/)
    {
		Interface::FITKOFGeometryData* geometryData = FITKAPP->getGlobalData()->getGeometryData<Interface::FITKOFGeometryData>();

		if (geometryData == nullptr)
		{
			return;
		}
		Interface::FITKAbsGeoCommand* model = geometryData->getDataByIndex(0);


		QString path = getValue("AFLR").toString();
		// 读取网格
		// 写出字典文件
		Interface::FITKUnstructuredFluidMeshVTK* mesh = FITKAPP->getGlobalData()->getMeshData<Interface::FITKUnstructuredFluidMeshVTK>();
		mesh->clearMesh();
		auto ofMeshReader = FITKAPP->getComponents()->getComponentTByName<IO::FITKOFMeshReader>("IO::FITKOFMeshReader");
		if(ofMeshReader == nullptr) return;
		ofMeshReader->setMeshFolder(path + "/mesh/");
		QString targetFolderPath = path + "/mesh/";
		QStringList fileNames = { "boundary", "neighbour", "owner", "faces", "points"};
		moveFilesToFolder(path, fileNames, targetFolderPath);
		ofMeshReader->setMeshObj(mesh);
		ofMeshReader->exec(0);


	}
	void FITKAFLRMeshProcessor::moveFilesToFolder(const QString & sourceFolderPath, const QStringList & fileNames, const QString & targetFolderPath)
	{
		QDir sourceDir(sourceFolderPath);
		if (!sourceDir.exists()) {
			qDebug() << "Source directory does not exist.";
			return;
		}

		QDir targetDir(targetFolderPath);
		if (!targetDir.exists()) {
			// 如果目标文件夹不存在，则创建它
			if (!targetDir.mkpath(".")) {
				qDebug() << "Failed to create target directory.";
				return;
			}
		}

		// 设置过滤器查找指定文件名的文件
		QStringList filters;
		for (const QString &name : fileNames) {
			filters << name;
		}
		sourceDir.setNameFilters(filters);
		sourceDir.setFilter(QDir::Files | QDir::NoDotAndDotDot);

		// 列出所有符合条件的文件并移动
		QStringList files = sourceDir.entryList();
		for (const QString &file : files) {
			QString sourcePath = sourceDir.absoluteFilePath(file);
			QString targetPath = targetDir.absoluteFilePath(file);
			if (QFile::exists(targetPath)) {
				QFile::remove(targetPath);  // 如果目标位置已存在文件，则先删除
			}
			if (QFile::rename(sourcePath, targetPath)) {
				qDebug() << "Moved:" << file << "to" << targetFolderPath;
			}
			else {
				qDebug() << "Failed to move:" << file;
			}
		}
	}
}



